package com.jinxin.platform.cdfaceacs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsDevice;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsOpenRecord;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsWorkDevice;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsWorker;
import com.jinxin.platform.cdfaceacs.bean.bo.AcsRecordUpData;
import com.jinxin.platform.cdfaceacs.common.SysUserVO;
import com.jinxin.platform.cdfaceacs.mapper.CdfaceacsWorkDeviceMapper;
import com.jinxin.platform.cdfaceacs.mapper.CdfaceacsWorkerMapper;
import com.jinxin.platform.cdfaceacs.service.IFaceAcsDeviceService;
import com.jinxin.platform.cdfaceacs.service.IFaceAcsRecordService;
import com.jinxin.platform.cdfaceacs.service.IFaceAcsWorkerService;
import com.jinxin.platform.cdfaceacs.utils.DateUtil;
import com.jinxin.platform.cdfaceacs.utils.IdWorker;
import com.jinxin.platform.cdfaceacs.utils.Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-03-02
 * @Author: Lingnan
 **/
@Api(tags = "门禁模块相关接口")
@RestController
@RequestMapping("/unAuth")
@Slf4j
public class FaceAcsUauthController {
    @Autowired
    private IFaceAcsRecordService recordService;
    @Autowired
    private IFaceAcsDeviceService deviceService;
    @Autowired
    private IFaceAcsWorkerService workerService;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private CdfaceacsWorkDeviceMapper workDeviceMapper;

    // 设备成功识别人员后，会向该地址POST 字段 ip 、personId 、time （识别时间）、
    // deviceKey、type：face/card_0/1/2 和path
    @PostMapping("/api/openRecordCallBack")
    public Map<String, Object> openRecordCallBack(HttpServletRequest request){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), StandardCharsets.UTF_8));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            String acceptjson = sb.toString();
            log.info("---------------识别回调:"+ acceptjson);
            AcsRecordUpData acsRecordUpData = JSON.parseObject(acceptjson, AcsRecordUpData.class);
            if(acsRecordUpData != null){
                CdfaceacsOpenRecord openRecord = new CdfaceacsOpenRecord();
                long timestamp = Long.parseLong(acsRecordUpData.getTime());
                openRecord.setOpenTime(DateUtil.getDateTimeOfTimestamp(timestamp));
                String deviceKey = acsRecordUpData.getDeviceKey();
                if(!StringUtils.isEmpty(deviceKey)){
                    HashMap param = new HashMap();
                    param.put("deviceKey",deviceKey);
                    CdfaceacsDevice device = deviceService.selectOne(param);
                    if(device != null){
                        openRecord.setSerialNum(device.getSerialNum());
                        openRecord.setDeviceName(device.getDeviceName());
                        openRecord.setDeviceArea(device.getDeviceArea());//进出方向
                    }
                }
                String openType;
                switch (acsRecordUpData.getType()){
                    case "face_0":
                    case "face_1":
                    case "face_2": openType = "刷脸识别";break;
                    case "card_0":
                    case "card_1": openType = "刷卡识别";break;
                    case "faceAndcard_0":
                    case "faceAndcard_1":
                    case "faceAndcard_2": openType = "双重认证";break;
                    default: openType = "未知";break;
                }
                openRecord.setRecordType(openType);
                // 由于是局域网，所以在外网获取不到抓拍图片。用人脸照片代替
                //openRecord.setCapturePic(acsRecordUpData.getPath());
                openRecord.setDeviceIp(acsRecordUpData.getIp());
                String personId = acsRecordUpData.getPersonId();
                if("STRANGERBABY".equals(personId)){
                    openRecord.setOpenUserId("STRANGERBABY");
                    openRecord.setOpenUser("[陌生人]");
                }else {
                    HashMap param = new HashMap();
                    param.put("personId",personId);
                    CdfaceacsWorkDevice workDevice = workDeviceMapper.selectOne(param);
                    if(workDevice != null){
                        CdfaceacsWorker workerInfo = workerService.selectById(workDevice.getWorkId());
                        if(workerInfo != null){
                            // 这里存的是设备的人员id，不能是人员id，因为同一个人可以授权给多台设备
                            openRecord.setOpenUserId(personId);
                            openRecord.setOpenUser(workerInfo.getName());
                            openRecord.setWorkType(workerInfo.getWorkType());
                            openRecord.setWorkTypeId(workerInfo.getWorkTypeId());
                            openRecord.setPhone(workerInfo.getPhone());
                            openRecord.setTeam(workerInfo.getTeam());
                            openRecord.setTeamId(workerInfo.getTeamId());
                            openRecord.setPersonCode(workerInfo.getPersonCode());
                            openRecord.setCapturePic(workerInfo.getFaceData());
                        }
                    }
                }
                if(!"STRANGERBABY".equals(openRecord.getOpenUserId())){
                    recordService.saveOrUpdate(openRecord);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("result",1);
        resMap.put("success",true);
        return resMap;
    }

    @ApiOperation(value = "考勤数据")
    @GetMapping("/faceacs/countWork")
    public JsonResult countWork(){
        HashMap param = new HashMap();
        int totalCount = workerService.listPageCount(param);
        param.put("workTypeId","01");//管理人员
        int mgrCount = workerService.listPageCount(param);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("totalCount",totalCount);
        resultMap.put("mgrCount",mgrCount);
        resultMap.put("workCount",(totalCount-mgrCount));
        int attendanceCount = recordService.countAttendance();
        resultMap.put("attendanceCount",attendanceCount);
        String attendanceRate = Utils.divide(attendanceCount,totalCount,2)*100+"%";
        resultMap.put("attendanceRate", attendanceRate);
        return JsonResult.ok("success",resultMap);
    }

    @RequestMapping("/faceacs/listOpenRecordOfCurrentDay")
    public JsonResult listOpenRecordOfCurrentDay(){
        HashMap param = new HashMap();
        param.put("isCurrentDay","true");
        return JsonResult.ok(recordService.list(param));
    }

    @ApiOperation(value = "人员进出记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="页码",required=true,paramType="query",dataType="Integer"),
            @ApiImplicitParam(name="limit",value="每页条数",required=true,paramType="query",dataType="Integer"),
            @ApiImplicitParam(name="workType",value="人员类型", paramType="query",dataType="String"),
            @ApiImplicitParam(name="openUser",value="名字", paramType="query",dataType="String"),
            @ApiImplicitParam(name="age",value="年龄", paramType="query",dataType="String"),
            @ApiImplicitParam(name="deviceArea",value="设备位置，进，出等", paramType="query",dataType="String")
    })
    @GetMapping("/faceacs/listOpenRecord")
    public JsonResult listOpenRecord(@RequestParam int page, @RequestParam int limit,
                                     @RequestParam(required = false) String workType, @RequestParam(required = false) String openUser,
                                     @RequestParam(required = false) String age, @RequestParam(required = false) String deviceArea){
        HashMap param = new HashMap();
        param.put("page", page);
        param.put("limit", limit);
        param.put("workType",workType);
        param.put("openUser",openUser);
        param.put("age",age);
        param.put("deviceArea",deviceArea);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("count",recordService.listOpenRecordCount(param));
        resultMap.put("data",recordService.listOpenRecord(param));
        return JsonResult.ok(resultMap);
    }

}
